<?php


    /**
    * @author NU SIT Bar
    * @version 1.0
    * @created 20.Jul.2012 8:43:39 h
    */
    class Gallery_model extends CI_Model
    {

        function __construct(){
            parent::__construct();

            $default_sizes = array (array('w'=>105,'h'=>79),array('w'=>454,'h'=>340));

            /*CREATE DEFAULT THUMBNAILS*/

            foreach($default_sizes as $d_size):

                $imortant_thumb_preview = $this->db->get_where('settings',array('name' => 'thumbnail_size'))->result_array();

                $create_default_thumb = TRUE;

                if(count($imortant_thumb_preview)>0){

                    foreach($imortant_thumb_preview as $thumb_size){
                        $dims = unserialize($thumb_size['user_data']);

                        if($dims['w']==$d_size['w'] && $dims['h']==$d_size['h']){
                            $create_default_thumb = FALSE;
                        }

                    }

                }

                if($create_default_thumb){

                    $this->db->insert('settings', array('name' => 'thumbnail_size', 'user_data' => serialize(array('w' => $d_size['w'], 'h' =>$d_size['h'])), 'description' => 'Default thumbnail for gallery preview <b>'.$d_size['w'].'x'.$d_size['h'].'<b>'));

                }  
                endforeach;

        }



        /**
        * 
        * @param post_type
        */
        function view_all($post_type=NULL)
        {     
            if(isset($post_type)){
                //$this->db->where("post_type= '".$post_type."' AND (parent_id = '0' OR parent_id is NULL)");
                $this->db->where("post_type = '$post_type' AND (parent_id = '0' OR parent_id is NULL)");   
            }else{
                $this->db->where("parent_id = '0' OR parent_id is NULL");
            }

            $res = $this->db->get('gallery')->result_array();

            return $res;
        }

        /**
        * 
        * @param post_type
        */
        function view_all_children($parent_ID)
        {
            $this->db->where('parent_id',$parent_ID);
            $res = $this->db->get('gallery')->result_array();

            return $res;
        }

        /**
        * 
        * @param gallery_ID
        */
        function view_edit($gallery_ID)
        {
            $this->db->where('ID',$gallery_ID);
            $res = $this->db->get('gallery')->row_array();
            return $res;
        }

        /**
        * 
        * @param post_type
        * @param gallery_name
        * @param parent_id
        */
        function add_gallery($post_type, $gallery_name, $parent_id)
        {
            //whitespace stripped from the beginning and end of string
            $gallery_name = trim($gallery_name);
            $gallery_name = str_replace(" ","_",$gallery_name);

            //add gallery
            $this->db->insert('gallery', array(
                    'title' => $gallery_name,
                    'post_type' => $post_type,
                    'parent_ID' => $parent_id,
                    'path' => "",
                    'pic_count' => 0,
                    'vid_count' => 0
                ));

            //go furhetr
            if($this->db->affected_rows()>0)
            {
                // add path to gallery
                $path = 'gall'.$this->db->insert_id().'-'.$gallery_name;
                $this->db->where('ID',$this->db->insert_id());
                $this->db->update('gallery', array('path' => $path)); 

                /**
                *
                * Create folders - structure
                * 
                * ./pro-gallery
                * 
                *   --> newgallery
                * 
                *       --> thumbnail
                *       --> videos
                * 
                *           --> thumbnail
                * 
                * */

                if (!file_exists("./pro-gallery")) {
                    if (!mkdir( "./pro-gallery", 0777)) {
                        die('Failed to create folder - pro-gallery -...');
                    }
                }

                if (!mkdir( "./pro-gallery/".$path, 0777)) {
                    die('Failed to create folder...');
                }else{

                    if (!mkdir( "./pro-gallery/".$path.'/thumbnail', 0777)) {
                        die('Failed to create folder...');
                    }else{

                        if (!mkdir( "./pro-gallery/".$path.'/videos', 0777)) {
                            die('Failed to create folder...');
                        }else{

                            if (!mkdir( "./pro-gallery/".$path.'/videos/thumbnail', 0777)) {
                                die('Failed to create folder...');
                            }else{

                                return TRUE;

                            }
                        }
                    } 
                }

            }
            else
            {
                return FALSE;
            }
        }

        /**
        * 
        * @param gallery_name
        * @param linkto
        * @param parent_id
        */
        function edit_gallery($gallery_ID, $gallery_name, $linkto, $parent_id)
        {

            //whitespace stripped from the beginning and end of string
            $gallery_name = trim($gallery_name);
            $gallery_name = str_replace(" ","_",$gallery_name);

            // automatic post_type conversion
            if($linkto!=0 && $linkto!=NULL){
                $post = $this->db->get_where('posts',array('ID'=>$linkto))->row_array();
                $post_type = $post['post_type'];

                //edit gallery
                $this->db->where('ID', $gallery_ID);
                $this->db->update('gallery', array(
                        'title' => $gallery_name,
                        'post_type' => $post_type,
                        'parent_ID' => $parent_id!=0  ?  $parent_id  :  NULL ,
                        'posts_ID' => $linkto ,
                    ));
            }else{

                //edit gallery 
                $this->db->where('ID', $gallery_ID);
                $this->db->update('gallery', array(
                        'title' => $gallery_name,
                        'parent_ID' => $parent_id!=0  ?  $parent_id  :  NULL
                    ));
            } 

            return TRUE;
        }

        /**
        * 
        * @param galleryselect  91<--delimiter!-->gall91-gal1 ( gallery_ID <--delimiter!--> path )
        * @param pictures => array
        * @param pic_titles => array
        */
        function add_pictures($galleryselect, $pictures, $pic_titles)
        {
            //Get gallery ID
            $gallery_id = explode('<--delimiter!-->',$galleryselect);
            $gallery_id = $gallery_id[0];

            //get dimensions
            $dimensions = $this->db->get_where('settings', array('name' => 'thumbnail_size'))->result_array();

            // img_map settings
            $path = './';

            //Get Gallert path
            $g_path =  $this->db->get_where('gallery', array('ID' => $gallery_id))->row_array();

            //Set images folder. (optional parameter)
            //Set cache folder. (must parameter)
            //Set jpeg quality
            //set image not found filepath. a must parameter. Output this image in case the image not found. 
            define("FOLDER_IMAGES",$path.'pro-gallery/'.$g_path['path'].'/');            
            define("FOLDER_CACHE",$path.'pro-gallery/'.$g_path['path'].'/thumbnail/');
            define("JPEG_QUALITY","90");            
            define("FILEPATH_IMAGE_NOT_FOUND",$path."assets/img/img_map/blank.jpg");

            //set defines data
            $this->img_map->setImagesFolder(FOLDER_IMAGES);
            $this->img_map->setCacheFolder(FOLDER_CACHE);
            $this->img_map->setErrorImagePath(FILEPATH_IMAGE_NOT_FOUND);
            $this->img_map->setJpegQuality(JPEG_QUALITY);  // end img_map settings

            //insert pictures
            $cnt = count($pictures);
            for($i=0;$i<$cnt;$i++){

                $this->db->insert('pictures',array(
                        'filename' => $pictures[$i],
                        'name' => $pic_titles[$i],
                        'date_time' => time(),
                        'gallery_ID' => $gallery_id               
                    ));

                foreach ($dimensions as $dimension):

                    //echo '<br>'.print_r($dimension).'<br>';

                    $dim = unserialize($dimension['user_data']);

                    //Create Thumbnails
                    $this->img_map->showImage($pictures[$i],$dim['w'],$dim['h'],"exacttop");

                    endforeach;

            }// end inser pictures

            //count number of pictures in gallery
            $this->db->where('gallery_ID',$gallery_id);
            $pic_count = $this->db->count_all_results('pictures');            

            //update gallery table
            $this->db->where('ID',$gallery_id);
            $this->db->update('gallery', array(
                    'pic_count' => $pic_count
                ));

            return TRUE;

        }

        /**
        * 
        * @param gallery_ID
        */ 
        function view_edit_images($gallery_ID)
        {            
            $this->db->where('gallery_ID',$gallery_ID);
            $this->db->order_by('order asc, ID asc');  
            $res = $this->db->get('pictures')->result_array();
            return $res;

        }

        /**
        * 
        * @param gallery_ID
        */
        function delete($gallery_ID)
        {
            $this->db->where('ID',$gallery_ID);
            $res = $this->db->get('gallery')->row_array();
            $path = $res['path'];


            $this->db->where('ID',$gallery_ID);
            $this->db->delete('gallery');

            if($this->db->affected_rows()>0){

                if($path!=''){
                    if($this->deleteDir("./pro-gallery/".$path)) {
                        return TRUE;
                    }else{
                        return FALSE;
                    }             
                }else return FALSE;   
            }else{
                return FALSE;
            }            
        }

        /**
        * 
        * @param picture_ID
        * @param gallery_ID
        */
        function delete_picture($picture_ID,$gallery_ID)
        {
            //get picture filename
            $p_filename =  $this->db->get_where('pictures', array('ID' => $picture_ID))->row_array();
            $pic_arr = explode('.',$p_filename['filename']);                     


            //delete picture
            $this->db->where('ID',$picture_ID);
            $this->db->delete('pictures');


            if($this->db->affected_rows()>0){

                //count number of pictures in gallery
                $this->db->where('gallery_ID',$gallery_ID);
                $pic_count = $this->db->count_all_results('pictures');            

                //update gallery table
                $this->db->where('ID',$gallery_ID);
                $this->db->update('gallery', array(
                        'pic_count' => $pic_count
                    ));

                //delete image and thumbnails
                $g_path =  $this->db->get_where('gallery', array('ID' => $gallery_ID))->row_array();

                unlink('./pro-gallery/'.$g_path['path'].'/'.$p_filename['filename']);

                //get dimensions
                $dim_arr = $this->db->get_where('settings', array('name' => 'thumbnail_size'))->result_array();

                //$dim_arr = array('105x79','221x117','223x148','469x283');

                foreach($dim_arr as $dim):

                    $d = unserialize($dim['user_data']);

                    $thumb_filename = $pic_arr[0].'_'.$d['w'].'x'.$d['h'].'_exacttop.'.$pic_arr[1];

                    //echo $thumb_filename.'<br>';

                    $path = './pro-gallery/'.$g_path['path'].'/thumbnail/'.$thumb_filename;
                    unlink($path);

                    endforeach; 

                return TRUE;           
            }else{
                return FALSE;
            }
        }


        /**
        * 
        * @param gallery_ID
        * @param picture_order => array
        */
        function picture_order($gallery_ID, $picture_order)
        {
            $pictures = $this->view_edit_images($gallery_ID);
            $nr = count($pictures);

            for ($k=0; $k<$nr; $k++) {

                $this->db->where('ID',$pictures[$k]['ID']);
                $this->db->update('pictures', array('order'=>$picture_order[$k])); 

            }

            return TRUE;
        }

        function create_thumbnails_again(){

            //crop and resize library
            $this->load->library('img_map');

            //get dimensions
            $dimensions = $this->db->get_where('settings', array('name' => 'thumbnail_size'))->result_array();

            //print_r($dimensions);

            $galleries = $this->db->query('SELECT * FROM gallery WHERE post_type IS NOT NULL')->result_array();

            //No galiers and No pictures
            //No need to create thumbnail
            if(!count($galleries)>0){
                echo 'No galiers and No pictures';
                return TRUE;
            }

            //print_r($galleries);

            //delete thumbnails folders and files within each gallery
            foreach ($galleries as $gallery):

                $this->deleteDir("./pro-gallery/".$gallery['path'].'/thumbnail');

                if (!mkdir( "./pro-gallery/".$gallery['path'].'/thumbnail', 0777)) {
                    die('Failed to create folder...');
                }else{ 


                    /* -----> THUMBNAIL IMAGE_MAP SETTINGS */           

                    //set defines data
                    $this->img_map->setImagesFolder('./pro-gallery/'.$gallery['path'].'/');
                    $this->img_map->setCacheFolder('./pro-gallery/'.$gallery['path'].'/thumbnail/');
                    $this->img_map->setErrorImagePath("./assets/img/img_map/blank.jpg");
                    $this->img_map->setJpegQuality("90");

                    /* ----->THUMBNAIL IMAGE_MAP SETTINGS */  

                    //create pictures

                    if ($handle = opendir('./pro-gallery/'.$gallery['path'].'/')) {

                        /* This is the correct way to loop over the directory. */
                        while (false !== ($entry = readdir($handle))) {
                            if ($entry != "." && $entry != ".." && $entry != "thumbnail" && $entry != "videos") {

                                foreach ($dimensions as $dimension):

                                    //echo '<br>'.print_r($dimension).'<br>';

                                    $dim = unserialize($dimension['user_data']);

                                    //Create Thumbnails
                                    $this->img_map->showImage($entry,$dim['w'],$dim['h'],"exacttop");

                                    endforeach;

                            }

                        }

                        closedir($handle);
                    }else{
                        echo 'no dir';
                    }

                }   

                endforeach;

            return TRUE;

        } 

        /**
        * 
        * Helper methot
        * 
        * Delete all files an folders in diretory and directory itself
        */
        function deleteDir($dir, $virtual = false)
        {
            $ds = DIRECTORY_SEPARATOR;
            $dir = $virtual ? realpath($dir) : $dir;
            $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
            if (is_dir($dir) && $handle = opendir($dir))
            {
                while ($file = readdir($handle))
                {
                    if ($file == '.' || $file == '..')
                    {
                        continue;
                    }
                    elseif (is_dir($dir.$ds.$file))
                    {
                        $this->deleteDir($dir.$ds.$file);
                    }
                    else
                    {
                        unlink($dir.$ds.$file);
                    }
                }
                closedir($handle);
                rmdir($dir);
                return true;
            }
            else
            {
                return false;
            }
        }

    }
?>
